package mine.code.day.year2021.month10;

import org.junit.Test;

/**
 * 给你一个非空数组，返回此数组中 第三大的数 。如果不存在，则返回数组中最大的数。
 * <p>
 * 示例 1：
 * <p>
 * 输入：[3, 2, 1]
 * 输出：1
 * 解释：第三大的数是 1 。
 *
 * @author caijinnan
 */
public class Day06_第三大的数 {

    @Test
    public void run() {
        int[] nums = {1, 2, 2, 4, 1, 2, 3};
        System.out.println(thirdMax(nums));
    }

    public int thirdMax(int[] nums) {
        long max = Long.MIN_VALUE;
        long secondMax = Long.MIN_VALUE;
        long thirdMax = Long.MIN_VALUE;
        for (int num : nums) {
            if (max == num || secondMax == num) {
                continue;
            }
            if (max < num) {
                thirdMax = secondMax;
                secondMax = max;
                max = num;
                continue;
            }
            if (secondMax <= num) {
                thirdMax = secondMax;
                secondMax = num;
                continue;
            }
            if (thirdMax <= num) {
                thirdMax = num;
            }
        }
        if (thirdMax == Long.MIN_VALUE) {
            return (int) max;
        }
        return (int) thirdMax;
    }
}
